package com.vehiclemanagement.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.vehiclemanagement.entity.Driver;
import com.vehiclemanagement.mapper.DriverMapper;
import com.vehiclemanagement.service.DriverService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 驾驶员服务实现类
 */
@Service
public class DriverServiceImpl extends ServiceImpl<DriverMapper, Driver> implements DriverService {

    @Autowired
    private DriverMapper driverMapper;

    @Override
    public IPage<Driver> pageDrivers(Integer current, Integer size, String searchTerm, String status, Boolean includeDeleted) {
        // 创建分页对象
        Page<Driver> page = new Page<>(current, size);
        
        // 创建自定义SQL条件
        String whereSql = " 1=1 ";
        
        // 添加搜索条件 - 支持多字段搜索
        if (StringUtils.isNotBlank(searchTerm)) {
            whereSql += " AND (name LIKE '%" + searchTerm + "%' OR department LIKE '%" + searchTerm + "%' OR license_number LIKE '%" + searchTerm + "%' OR phone LIKE '%" + searchTerm + "%') ";
        }
        
        // 添加状态查询条件
        if (StringUtils.isNotBlank(status)) {
            whereSql += " AND status = '" + status + "' ";
        }
        
        // 处理删除标志
        if (Boolean.TRUE.equals(includeDeleted)) {
            // 查询已删除的驾驶员
            System.out.println("查询已删除的驾驶员");
            whereSql += " AND del_flag = 1 ";
        } else {
            // 默认查询未删除的驾驶员
            System.out.println("只查询未删除的驾驶员");
            whereSql += " AND del_flag = 0 ";
        }
        
        // 添加排序
        whereSql += " ORDER BY create_time DESC";
        
        System.out.println("执行查询SQL条件: " + whereSql);
        
        // 执行查询
        return driverMapper.selectPageWithDeleted(page, whereSql);
    }

    @Override
    public Driver getDriverById(Long id) {
        return driverMapper.selectById(id);
    }

    @Override
    public boolean addDriver(Driver driver) {
        System.out.println("服务层开始添加驾驶员: " + driver);
        
        try {
            // 设置默认值
            if (driver.getCreateTime() == null) {
                driver.setCreateTime(LocalDateTime.now());
            }
            if (driver.getUpdateTime() == null) {
                driver.setUpdateTime(LocalDateTime.now());
            }
            if (driver.getDelFlag() == null) {
                driver.setDelFlag(0);
            }
            
            // 执行插入
            int result = driverMapper.insert(driver);
            System.out.println("插入结果: " + result + ", 生成的ID: " + driver.getId());
            
            return result > 0;
        } catch (Exception e) {
            System.err.println("添加驾驶员发生异常: " + e.getMessage());
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public boolean updateDriver(Driver driver) {
        // 更新时间
        driver.setUpdateTime(LocalDateTime.now());
        
        return driverMapper.updateById(driver) > 0;
    }

    @Override
    public boolean deleteDriver(Long id) {
        // 使用物理删除
        System.out.println("执行物理删除驾驶员，ID: " + id);
        
        try {
            // 先查询出驾驶员信息，方便记录日志
            Driver driver = driverMapper.selectById(id);
            if (driver != null) {
                System.out.println("准备物理删除姓名为 " + driver.getName() + " 的驾驶员");
                
                // 直接物理删除记录
                int result = driverMapper.deletePhysically(id);
                System.out.println("物理删除结果: " + result);
                return result > 0;
            } else {
                System.out.println("未找到ID为 " + id + " 的驾驶员，无法删除");
                return false;
            }
        } catch (Exception e) {
            System.err.println("删除驾驶员时出错: " + e.getMessage());
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public List<String> getDepartments() {
        // 查询所有驾驶员，然后提取不重复的部门
        LambdaQueryWrapper<Driver> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.select(Driver::getDepartment);
        queryWrapper.groupBy(Driver::getDepartment);
        queryWrapper.ne(Driver::getDepartment, ""); // 排除空字符串
        queryWrapper.isNotNull(Driver::getDepartment); // 排除 null 值
        
        List<Driver> drivers = driverMapper.selectList(queryWrapper);
        return drivers.stream()
                .map(Driver::getDepartment)
                .distinct()
                .collect(Collectors.toList());
    }
} 